angular.module("m",[])
    .controller("c",function ($scope) {
        /**定义基本信息**/
        $scope.infoObj = {
            appKey:"ab1c052dadc6f45709f55bdd7cb0c347",
            appSecret:"2e01add3ae8c",
            user:[{
                accid:"test02",
                token:"6950d7b1c6c74d0e0a37b26ec2dbb273",
                text:""
            },{
                accid:"test03",
                token:"ef00cb45cfa89ddd4beecdb9bfb25f61",
                text:""
            },{
                accid:"test04",
                token:"324193fff029b43af93ece11f3c2e3c1",
                text:""
            }]
        };
        /**初始化云信sdk**/
        //用户2 3 4
        //连接池
        $scope.connArray = [];
        //配置对象
        $scope.configObj = {
            appKey: $scope.infoObj.appKey,
            account: "",
            token: "",
            onconnect: function () {
                console.log('登录成功');
            },
            onwillreconnect: function (obj) {
                console.log('即将重连');
                console.log(obj.retryCount);
                console.log(obj.duration);
            },
            ondisconnect: function (error) {
                console.log('丢失连接');
                console.log(error);
                if (error) {
                    switch (error.code) {
                        // 账号或者密码错误, 请跳转到登录页面并提示错误
                        case 302:
                            break;
                        // 重复登录, 已经在其它端登录了, 请跳转到登录页面并提示错误
                        case 417:
                            break;
                        // 被踢, 请提示错误后跳转到登录页面
                        case 'kicked':
                            break;
                        default:
                            break;
                    }
                }
            },
            onerror: function (error) {
                console.log(error);
            },
            /**收到消息**/
            onmsg: function(msg) {
                console.log('收到消息', msg.scene, msg.type, msg);
                switch (msg.type) {
                    case 'custom':
                        break;
                    case 'notification':
                        // 处理群通知消息
                        break;
                    default:
                        break;
                }
            },
            onroamingmsgs: function(obj) {
                console.log('收到漫游消息', obj);
            },
            onofflinemsgs: function(obj) {
                console.log('收到离线消息', obj);
            }
        };
        for(var i=0;i<3;i++){
            $scope.configObj.account = $scope.infoObj.user[i].accid;
            $scope.configObj.token = $scope.infoObj.user[i].token;
            //console.log($scope.configObj);
            $scope.connArray.push(NIM.getInstance($scope.configObj));//获取实例
        }
        /**发送消息**/
        $scope.preSend = function (index) {
            if($scope.infoObj.user[index].text==""||$scope.infoObj.user[index].text==null){
                return ;
            }
            $scope.sendText($scope.connArray[index],//连接实例
                {to:"zzk-001",//accid
                text:$scope.infoObj.user[index].text
            });
        };
        $scope.sendText = function (nim,obj) {
            nim.sendText({
            //nim.sendCustomMsg({
                scene: 'p2p',
                to: obj.to,
                text: obj.text,
                //content: JSON.stringify({"ext":"custome message"}),
                done: function(error, msg) {
                    console.log(error);
                    console.log(msg);
                    console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient);
                }
            });
        };
        /**清空消息**/
        $scope.clearText = function (index) {
            $scope.infoObj.user[index].text = "";
        };
        /**发送图片**/
        sendImg = function (dataURL) {
            var nim = $scope.connArray[0];
            nim.previewFile({
                type: 'image',
                //fileInput: document.getElementById("fileUpload"),
                dataURL:dataURL,
                uploadprogress: function(obj) {
                    /*console.log('文件总大小: ' + obj.total + 'bytes');
                     console.log('已经上传的大小: ' + obj.loaded + 'bytes');
                     console.log('上传进度: ' + obj.percentage);
                     console.log('上传进度文本: ' + obj.percentageText);*/
                    console.log(obj);//整个对象
                    //$("#proId").css('width', obj.percentage+"%");
                    //$("#proId").children("span").html(obj.percentage+"");
                },
                done: function(error, file) {
                    console.log('上传image' + (!error?'成功':'失败'));
                    console.log(file);
                    // show file to the user
                    if (!error) {
                     var msg = nim.sendFile({
                     scene: 'p2p',
                     to: "test01",
                     file: file,
                     text:"this is file",
                     done: function(error, msg) {
                     console.log(error);
                     console.log(msg);
                     console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient);
                     }
                     });
                     console.log('正在发送p2p image消息, id=' + msg.idClient);
                     }
                }
            });
        };
        /**JS图片压缩（pc端和移动端都适用）**/
        function dealImage(path, obj, callback){
            var img = new Image();
            img.src = path;
            img.onload = function(){
                var that = this;
                // 默认按比例压缩
                var w = that.width,
                    h = that.height,
                    scale = w / h;
                w = obj.width || w;
                h = obj.height || (w / scale);
                var quality = 0.7;  // 默认图片质量为0.7
                //生成canvas
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                // 创建属性节点
                var anw = document.createAttribute("width");
                anw.nodeValue = w;
                var anh = document.createAttribute("height");
                anh.nodeValue = h;
                canvas.setAttributeNode(anw);
                canvas.setAttributeNode(anh);
                ctx.drawImage(that, 0, 0, w, h);
                // 图像质量
                if(obj.quality && obj.quality <= 1 && obj.quality > 0){
                    quality = obj.quality;
                }
                // quality值越小，所绘制出的图像越模糊
                var base64 = canvas.toDataURL('image/jpeg', quality);
                // 回调函数返回base64的值
                callback(base64);
            }
        }
        changeInput = function () {
            //获取文件
            var file = document.getElementById("fileUpload").files[0];
            //创建读取文件的对象
            var reader = new FileReader();
            //创建文件读取相关的变量
            var imgFile;
            //为文件读取成功设置事件
            reader.onload=function(e) {
                console.log('文件读取完成');
                imgFile = e.target.result;//base64
                //console.log(imgFile);
                //$("#imgContent-yuan").attr('src', imgFile);//原图
                dealImage(imgFile,{
                    quality:0.7
                },function (imgFile) {
                    //$("#imgContent").attr('src', imgFile);//压缩图
                    sendImg(imgFile);
                });
            };
            //正式读取文件
            reader.readAsDataURL(file);
        };
    });